<template>
  <div id="DrugInformation">
    <div class="header-container">
      <div class="header-title">
        <i class="el-icon-medical title-icon"></i>
        <h1>药品信息管理</h1>
      </div>
      
      <div class="search-container">
        <el-input placeholder="请输入ID" prefix-icon="el-icon-search" v-model="drug_id" size="medium" 
            class="header-input" clearable />
        <el-input placeholder="请输入药名" prefix-icon="el-icon-search" v-model="drug_name" size="medium"
            class="header-input" clearable />
        <el-select v-model="company_name" placeholder="请选择药品公司" size="medium" class="header-select" clearable>
          <el-option v-for="item in drugCompanyList" :key="item.company_id" :label="item.company_name"
              :value="item.company_name" />
        </el-select>
        <el-button id="search" type="primary" icon="el-icon-search" @click="search()" size="medium"
            class="header-btn">搜索</el-button>
        <el-button id="reset" type="info" icon="el-icon-refresh" @click="resetSearch()" size="medium"
            class="header-btn">重置</el-button>
      </div>
      
      <el-button type="success" class="add-button header-btn" icon="el-icon-circle-plus" @click="addDrug()" size="medium">新增药品</el-button>
    </div>

    <el-card class="table-card">
      <el-table :data="pm.list" border style="width: 100%" class="drug-table">
        <el-table-column fixed prop="drug_id" label="ID" width="80" align="center">
          <template slot-scope="scope">
            <el-tag size="medium" type="primary">{{ scope.row.drug_id }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="drug_name" label="药名" width="150" align="center">
          <template slot-scope="scope">
            <span class="drug-name">{{ scope.row.drug_name }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="drug_img" label="药品图片" width="120" align="center">
          <template slot-scope="scope">
            <el-image 
              :src="getImageUrl(scope.row.drug_img)" 
              :preview-src-list="[getImageUrl(scope.row.drug_img)]"
              fit="cover"
              style="width: 80px; height: 60px; border-radius: 6px;"
              v-if="scope.row.drug_img">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <span v-else class="no-image">暂无图片</span>
          </template>
        </el-table-column>

        <el-table-column prop="drug_info" label="药品成分信息" min-width="200" show-overflow-tooltip>
        </el-table-column>

        <el-table-column prop="drug_effect" label="药品功能" min-width="250" show-overflow-tooltip>
        </el-table-column>

        <el-table-column prop="publisher" label="发布者" width="100" align="center">
        </el-table-column>

        <el-table-column prop="drugCompany.company_name" label="药品公司" width="150" align="center">
          <template slot-scope="scope">
            <el-tag size="small" type="info">{{ scope.row.drugCompany.company_name }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="150" align="center">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="updateDrug(scope.row)" size="mini" circle title="编辑"></el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteDrug(scope.row.drug_id)" size="mini" circle title="删除"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="pm.totalRecords"
      :page-size="pm.pageSize" :current-page="pm.currentPageNum" :page-sizes="[5, 10, 20, 50]" @size-change="sizeChange"
      @current-change="pageChange" style="margin-top: 20px; text-align: center;" class="pagination-container">
    </el-pagination>

    <el-dialog title="编辑药品信息" :visible.sync="updateFormvisible" :modal-append-to-body="false" width="600px" class="drug-dialog">
      <div class="dialog-content">
        <el-form :model="drug" :label-width="'100px'" label-position="left">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="药名">
                <el-input v-model="drug.drug_name" placeholder="请输入药名"></el-input>
              </el-form-item>

              <el-form-item label="药品成分">
                <el-input v-model="drug.drug_info" type="textarea" :rows="3" placeholder="请输入药品成分信息"></el-input>
              </el-form-item>

              <el-form-item label="药品功能">
                <el-input v-model="drug.drug_effect" type="textarea" :rows="3" placeholder="请输入药品功能"></el-input>
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="药品图片">
                <el-upload 
                  class="avatar-uploader" 
                  action="http://localhost:8080/upload"
                  :show-file-list="false" 
                  :on-success="handleAvatarSuccess" 
                  :before-upload="beforeAvatarUpload"
                  name="file">
                  <img v-if="drug.drug_img" :src="getImageUrl(drug.drug_img)" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <div class="upload-tip">支持 JPG/PNG/GIF 格式，文件大小不超过 5MB</div>
              </el-form-item>

              <el-form-item label="发布者">
                <el-input v-model="drug.publisher" placeholder="请输入发布者"></el-input>
              </el-form-item>

              <el-form-item label="药品公司">
                <el-select v-model="drug.drugCompany.company_id" placeholder="请选择药品公司" style="width: 100%;">
                  <el-option v-for="item in drugCompanyList" :key="item.company_id" :label="item.company_name"
                    :value="item.company_id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelUpdate()">取 消</el-button>
        <el-button type="primary" @click="submmitUpdate()">提 交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="新增药品" :visible.sync="addFormvisible" :modal-append-to-body="false" width="600px" class="drug-dialog">
      <div class="dialog-content">
        <el-form :model="drug" :label-width="'100px'" label-position="left">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="药名">
                <el-input v-model="drug.drug_name" placeholder="请输入药名"></el-input>
              </el-form-item>

              <el-form-item label="药品成分">
                <el-input v-model="drug.drug_info" type="textarea" :rows="3" placeholder="请输入药品成分信息"></el-input>
              </el-form-item>

              <el-form-item label="药品功能">
                <el-input v-model="drug.drug_effect" type="textarea" :rows="3" placeholder="请输入药品功能"></el-input>
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="药品图片">
                <el-upload 
                  class="avatar-uploader" 
                  action="http://localhost:8080/upload"
                  :show-file-list="false" 
                  :on-success="handleAvatarSuccess" 
                  :before-upload="beforeAvatarUpload"
                  name="file">
                  <img v-if="drug.drug_img" :src="getImageUrl(drug.drug_img)" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <div class="upload-tip">支持 JPG/PNG/GIF 格式，文件大小不超过 5MB</div>
              </el-form-item>

              <el-form-item label="发布者">
                <el-input v-model="drug.publisher" placeholder="请输入发布者"></el-input>
              </el-form-item>

              <el-form-item label="药品公司">
                <el-select v-model="drug.drugCompany.company_id" placeholder="请选择药品公司" style="width: 100%;">
                  <el-option v-for="item in drugCompanyList" :key="item.company_id" :label="item.company_name"
                    :value="item.company_id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd()">取 消</el-button>
        <el-button type="primary" @click="submmitAdd()">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: "DrugInformation",
  data() {
    return {
      drug_id: null,
      drug_name: "",
      company_name: "",
      updateFormvisible: false,
      addFormvisible: false,
      pm: {
        currentPageNum: 1,
        totalRecords: 0,
        pageSize: 5,
        totalPageNum: 0,
        startIndex: 0,
        prePageNum: 0,
        nextPageNum: 0,
        list: [],
        startPage: 0,
        endPage: 0
      },
      drug: {
        drug_id: null,
        drug_name: "",
        drug_img: "",
        drug_info: "",
        drug_effect: "",
        publisher: "",
        drugCompany: {
          company_id: null,
          company_name: "",
          company_phone: ""
        }
      },
      drugCompanyList: []
    }
  },
  mounted() {
    this.getDrugPage(1);
    this.getDrugCompanyList();
  },
  methods: {
    getDrugPage(e) {
      axios.get("http://localhost:8080/getDrugPage", { params: { num: e, size: this.pm.pageSize } }).then(res => {
        this.pm = res.data
      })
    },
    sizeChange(size) {
      this.pm.pageSize = size;
      this.getDrugPage(1);
    },
    pageChange(num) {
      this.getDrugPage(num);
    },
    deleteDrug(drug_id) {
      this.$confirm('确定删除该药品信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete("http://localhost:8080/deleteDrug", { params: { drug_id } }).then(res => {
          this.$message.success(res.data);
          this.getDrugPage(1);
        }).catch(() => {
          this.$message.error('删除失败');
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    updateDrug(dg) {
      this.updateFormvisible = true;
      this.drug = JSON.parse(JSON.stringify(dg));
      this.getDrugCompanyList();
    },
    submmitUpdate() {
      axios.put("http://localhost:8080/updateDrug", this.drug).then(res => {
        this.$message.success(res.data);
        this.updateFormvisible = false;
        this.getDrugPage(this.pm.currentPageNum);
        this.resetDrug();
      }).catch(() => {
        this.$message.error('更新失败');
      });
    },
    addDrug() {
      this.getDrugCompanyList();
      this.addFormvisible = true;
    },
    cancelUpdate() {
      this.updateFormvisible = false;
      this.resetDrug();
    },
    submmitAdd() {
      axios.post("http://localhost:8080/addDrug", this.drug).then(res => {
        this.$message.success(res.data);
        this.addFormvisible = false;
        this.getDrugPage(this.pm.currentPageNum);
        this.resetDrug();
      }).catch(() => {
        this.$message.error('添加失败');
      });
    },
    cancelAdd() {
      this.addFormvisible = false;
      this.resetDrug();
    },
    getDrugCompanyList() {
      axios.get("http://localhost:8080/getAllDrugCompany").then(res => {
        this.drugCompanyList = res.data;
      })
    },
    resetDrug() {
      this.drug = {
        drug_id: null,
        drug_name: "",
        drug_img: "",
        drug_info: "",
        drug_effect: "",
        publisher: "",
        drugCompany: {
          company_id: null,
          company_name: "",
          company_phone: ""
        }
      }
    },
    search() {
      axios.get("http://localhost:8080/getDrugByConditions", { params: { drug_id: this.drug_id, drug_name: this.drug_name, company_name: this.company_name } }).then(res => {
        this.pm.list = res.data;
      })
    },
    resetSearch() {
      this.resetConditions();
      this.getDrugPage(1);
    },
    resetConditions() {
      this.drug_id = null;
      this.drug_name = "";
      this.company_name = "";
    },
    handleAvatarSuccess(res) {
      if (res && res.startsWith('/uploads/')) {
        this.drug.drug_img = res;
        this.$message.success('图片上传成功');
      } else {
        this.$message.error('图片上传失败');
      }
    },
    beforeAvatarUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!');
        return false;
      }
      return true;
    },
    getImageUrl(imgPath) {
      if (!imgPath) return '';
      if (imgPath.startsWith('http')) {
        return imgPath;
      }
      return `http://localhost:8080${imgPath}`;
    }
  }
}
</script>

<style scoped>
#DrugInformation {
  width: 100%;
  height: 100%;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf9 100%);
  min-height: calc(100vh - 40px);
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(120deg, #ffffff 0%, #f8f9ff 100%);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #e6ebf5;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-title h1 {
  font-size: 26px;
  margin: 0;
  background: linear-gradient(90deg, #409eff, #64b5f6);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-weight: 600;
}

.title-icon {
  font-size: 28px;
  color: #409eff;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-input,
.header-select {
  width: 180px;
  height: 40px;
  border-radius: 20px;
}

.header-input ::v-deep .el-input__inner,
.header-select ::v-deep .el-input__inner {
  border-radius: 20px;
}

.header-btn {
  height: 40px;
  min-width: 90px;
  padding: 0 16px;
  font-size: 14px;
  border-radius: 20px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.header-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
}

.add-button {
  background: linear-gradient(120deg, #67c23a, #95d475);
  border: none;
  color: white;
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #e6ebf5;
  overflow: hidden;
}

.drug-table {
  border-radius: 12px;
}

.drug-table ::v-deep .el-table__header th {
  background-color: #f0f5ff;
  color: #333;
  font-weight: 600;
}

.drug-table ::v-deep .el-table__row:hover {
  background-color: #f5f9ff;
  transition: background-color 0.3s;
}

.drug-name {
  font-weight: 500;
  color: #409eff;
}

.no-image {
  color: #909399;
  font-size: 12px;
}

.pagination-container {
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.pagination-container ::v-deep .el-pagination button,
.pagination-container ::v-deep .el-pagination span:not([class*=suffix]) {
  border-radius: 6px;
}

.pagination-container ::v-deep .el-pagination .el-pager li {
  border-radius: 6px;
  margin: 0 2px;
}

.pagination-container ::v-deep .el-pagination .el-pager li.active {
  background-color: #409eff;
  color: white;
}

.drug-dialog ::v-deep .el-dialog {
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.drug-dialog ::v-deep .el-dialog__header {
  background: linear-gradient(120deg, #f5f7fa 0%, #eef2f7 100%);
  border-bottom: 1px solid #e6ebf5;
  border-radius: 12px 12px 0 0 !important;
  padding: 20px;
}

.drug-dialog ::v-deep .el-dialog__title {
  font-weight: 600;
  color: #303133;
  font-size: 18px;
}

.dialog-content {
  padding: 20px;
}

.drug-dialog .el-form-item {
  margin-bottom: 22px;
}

.drug-dialog ::v-deep .el-form-item__label {
  font-weight: 500;
  color: #555;
}

.dialog-footer {
  text-align: right;
  padding: 15px 20px;
  border-top: 1px solid #e6ebf5;
  background-color: #f5f7fa;
  border-radius: 0 0 12px 12px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
  border-radius: 6px;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
  border-radius: 6px;
}

::v-deep .el-tag {
  border-radius: 12px;
}

::v-deep .el-button--mini {
  border-radius: 50%;
  padding: 5px;
}
</style>